var path = require("path");
var fs = require("fs");
var fsp = require("fs/promises");

// var str = "http://localhost.com:5500/html/index.html?name=huaishuang&age=18#one";

// 将site作为服务器的默认站点路径
var siteUrl = "../../site";
var defaultSite = path.join(__dirname, siteUrl);
var defaultEncode = "utf-8";

/**
 * 读取并渲染文件
 *
 * @param {*} pathname  读取的文件路径
 * @param {*} res       响应对象
 */
function renderFile(pathname, res) {
    var readPath = path.join(defaultSite, pathname);
    // console.log(readPath);

    if (fs.existsSync(readPath)) { // 是否存在文件和文件夹

        fsp.stat(readPath).then(info => {
            if (info.isFile()) {
                var ext = path.extname(pathname);
                // console.log(ext);

                if ([".html"].includes(ext)) {
                    fsp.readFile(readPath, defaultEncode).then(data => {
                        res.writeHead(200, {
                            "Content-Type": "text/html;charset=utf-8"
                        })
                        res.end(data);
                    })
                } else if ([".css"].includes(ext)) {
                    fsp.readFile(readPath, defaultEncode).then(data => {
                        res.writeHead(200, {
                            "Content-Type": "text/css;charset=utf-8"
                        })
                        res.end(data);
                    })
                } else if ([".js"].includes(ext)) {
                    fsp.readFile(readPath, defaultEncode).then(data => {
                        res.writeHead(200, {
                            "Content-Type": "text/javascript;charset=utf-8"
                        })
                        res.end(data);
                    })
                } else if ([".jpg", ".jpeg", ".png", ".gif"].includes(ext)) {
                    fsp.readFile(readPath, "binary").then(data => {
                        // console.log(111111);
                        res.end(data, "binary");
                    })
                } else {
                    fsp.readFile(readPath, defaultEncode).then(data => {
                        res.end(data);
                    })
                }

            } else if (info.isDirectory()) {
                let dafaultRead = path.join(readPath, "./index.html");
                fsp.readFile(dafaultRead, defaultEncode).then(data => {
                    res.writeHead(200, {
                        "Content-Type": "text/html;charset=utf-8"
                    })
                    res.end(data);
                })
            }
        }).catch(err => {
            console.log("文件有误 at renderFile.js");
            throw err;
        })


    } else {
        return false;
    }
}

module.exports = { renderFile }; 